package aaa;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @Title: UDPClient
 * @Author 郑雨杭
 * @Package aaa
 * @Date 2024/7/10 19:04
 * @description:
 */
public class UDPClient {
    //定义一个UDP的socket，即DatagramSocket
    private DatagramSocket socket = null;
    //服务器端ip
    private String ip;
    //服务器端端口
    private int port;

    //初始化socket，服务器ip和端口
    public UDPClient(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        this.ip = ip;
        this.port = port;
    }

    public void stact() throws IOException {
        //提示信息
        System.out.println("客户端连接");
        //准备输入
        Scanner scanner = new Scanner(System.in);
        //循环发送请求
        while (true){
            //提示输入请求
            System.out.print("请输入：");
            //输入请求
            String req =scanner.nextLine();
            //创建发送给服务器的数据报
            DatagramPacket p = new DatagramPacket(req.getBytes(),req.getBytes().length, InetAddress.getByName(ip),port);
            //发送数据报
            socket.send(p);
            //准备构造接收响应的数据报
            byte[] rem = new byte[4096];
            //创建接收响应的数据报
            DatagramPacket ret = new DatagramPacket(rem,0,rem.length);
            //接收响应
            socket.receive(ret);
            //将响应转换为字符串
            String r = new String(ret.getData(),0,ret.getLength());
            //打印响应到控制台
            System.out.println(r);
        }
    }

    //启动客户端，并且绑定服务器
    public static void main(String[] args) throws IOException {
        new UDPClient("127.0.0.1",9090).stact();
    }
}
